package com.x.epspace.service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import com.x.epspace.dao.BindLimitDao;
import com.x.epspace.entity.BindLimit;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.QueryResults;
import org.springframework.stereotype.Service;

import com.x.epspace.common.AppConfig;
import com.x.epspace.common.HttpRequestor;
import com.x.epspace.common.Tool;
import com.x.epspace.dao.BindEntDao;
import com.x.epspace.dao.RegUserDao;
import com.x.epspace.entity.BindEnt;
import com.x.epspace.entity.IdentObj;
import com.x.epspace.entity.RegUser;
import com.x.epspace.ext.HandleSessionService;

@Service("bindEntService")
public class BindEntService {
	
	private static final Log log = LogFactory.getLog(BindEntService.class);
	
	@Resource
	private HandleSessionService handleSession;
	
	@Resource
	private BindEntDao bindEntDao;
	
	@Resource
	private RegUserDao regUserDao;

    @Resource
    private BindLimitDao bindLimitDao;
	
	/**
	 * 校验并绑定企业信息
	 * @param szch      注册号
	 * @param sqymc     企业名称
	 * @param identCode 证件号码
	 * @param identName 股东姓名
	 * @return
	 */
	public Map<String, String> validBindEnt(String szch,String sqymc,String identCode,String identName,String identType,String fzr,String fzrzjhm){
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
		//获取session用户信息
		Object regUserObj = handleSession.getVal(AppConfig.getProperty("USER_SESSION_KEY","SESSION_KEY"));
		if (regUserObj == null){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "用户未登录");
			return returnMap;
		}
		RegUser regUser = (RegUser)regUserObj;
        //验证该企业是否在限定表中
        boolean limitFlag = false;
        Query<BindLimit> bindLimitQuery = bindLimitDao.createQuery();
        bindLimitQuery.field("sqymc").equal(sqymc);
        QueryResults<BindLimit> bindLimits = bindLimitDao.find(bindLimitQuery);
        //如果在限定表中，需判断用户手机号是否可绑定该企业
        if(bindLimits!=null){
			List<BindLimit> bindLimitList = bindLimits.asList();
			if(bindLimitList.size()>0) {
				limitFlag = true;
				for (BindLimit bindLimit : bindLimitList) {
					if (bindLimit.getMobile().equals(regUser.getMobile())) {
						//允许该手机绑定该企业
						limitFlag = false;
						break;
					}
				}
			}
        }
        if(limitFlag){
            returnMap.put("result",
                    AppConfig.getProperty("fail", "return_code"));
            returnMap.put("description", "您不能绑定该企业");
            return returnMap;
        }

		//验证该用户是否已绑定该企业
		Query<BindEnt> qEnt = bindEntDao.createQuery();
		qEnt.field("regUser").equal(regUser).field("szch").equal(szch);
		long bindCount = bindEntDao.count(qEnt);
		if(bindCount>0){//已绑定过
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "您已绑定过该企业");
			return returnMap;
		}

		try{
			//验证企业信息是否正确
			Map<String,String> paramMap = new HashMap<String,String>();
			paramMap.put("szch", URLEncoder.encode(szch,"utf-8"));
			paramMap.put("sqymc", URLEncoder.encode(sqymc,"utf-8"));
			paramMap.put("identCode", URLEncoder.encode(identCode,"utf-8"));
			paramMap.put("identName", URLEncoder.encode(identName,"utf-8"));
			paramMap.put("identType", identType);
			paramMap.put("fzr", URLEncoder.encode(fzr,"utf-8"));
			paramMap.put("fzrzjhm", URLEncoder.encode(fzrzjhm,"utf-8"));
			String returnJson = HttpRequestor.doPost(AppConfig.getProperty("validEntUrl", "system"), paramMap);
			if(!Tool.isNotNullOrEmpty(returnJson)){
				returnMap.put("result",
						AppConfig.getProperty("fail", "return_code"));
				returnMap.put("description", "企业信息验证未通过");
				return returnMap;
			}
			JSONObject json=JSONObject.fromObject(returnJson);
			String result = json.getString("result");
			if(!result.equals(AppConfig.getProperty("success", "return_code"))){
				returnMap.put("result",
						AppConfig.getProperty("fail", "return_code"));
				returnMap.put("description", json.getString("description"));
				return returnMap;
			}
			//验证通过，保存绑定企业信息
			JSONObject qyxxObj = json.getJSONObject("qyxx");
			String snbxh = qyxxObj.getString("snbxh");
			String real_szch  = qyxxObj.getString("szch");
            try {
                saveBindEnt(regUser, snbxh, real_szch, sqymc, identCode, identName, fzr, fzrzjhm, identType);
            }catch (Exception e){
                returnMap.put("result",
                        AppConfig.getProperty("fail", "return_code"));
				String errMsg = e.getMessage();
				if(errMsg.indexOf("regUser_1_szch_1") > 0){
					returnMap.put("description", "您已绑定过该企业,无需重复绑定");
				}else{
					returnMap.put("description", errMsg);
				}

                return returnMap;
            }
			returnMap.put("result",
					AppConfig.getProperty("success", "return_code"));
			returnMap.put("description", "验证通过,绑定企业成功");
			return returnMap;
		}catch(Exception e){
			log.error(e);
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "校验并绑定企业信息出错");
			return returnMap;
		}
		
	}
	
	
	/**
	 * 保存企业信息到session
	 * @param bindEnt
	 */
	public void setBindEntToSession(BindEnt bindEnt){
		//保存当前企业信息到session
		handleSession.setVal(AppConfig.getProperty("ENT_SESSION_KEY", "SESSION_KEY"), bindEnt);
	}
	
	/**
	 * 选择一个绑定的企业身份登录
	 * @param snbxh
	 * @return
	 */
	public Map<String,String> selectBindEntLogin(String snbxh){
		//初始化返回
		Map<String, String> returnMap = new HashMap<String, String>();
		if(!Tool.isNotNullOrEmpty(snbxh)){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "参数为空");
			return returnMap;
		}
		//获取session用户信息
		Object regUserObj = handleSession.getVal(AppConfig.getProperty("USER_SESSION_KEY","SESSION_KEY"));
		if (regUserObj == null){
			returnMap.put("result",
							AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "用户未登录");
			return returnMap;
		}
		RegUser regUser = (RegUser)regUserObj;
		//提取该用户绑定的该企业信息
		Query<BindEnt> qEnt = bindEntDao.createQuery();
		qEnt.field("regUser").equal(regUser).field("snbxh").equal(snbxh);
		BindEnt bindEnt = bindEntDao.findOne(qEnt);
		if(bindEnt == null){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "用户未绑定该企业");
			return returnMap;
		}
		if(!bindEnt.getIdentStatus().equals(AppConfig.getProperty("status_normal", "status_code"))){
			returnMap.put("result",
					AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "用户绑定企业信息状态已无效");
			return returnMap;
		}
		//保存当前企业信息到session
		handleSession.setVal(AppConfig.getProperty("ENT_SESSION_KEY", "SESSION_KEY"), bindEnt);
		returnMap.put("result",
				AppConfig.getProperty("success", "return_code"));
		returnMap.put("description", "已成功选择企业身份登录");
		return returnMap;
	}
	
	private void saveBindEnt(RegUser regUser,String snbxh,String szch,String sqymc,String identCode,String identName,String fzr,String fzrzjhm,String identType) throws Exception{
		//保存绑定企业信息
		BindEnt bindEnt = new BindEnt();
		bindEnt.setRegUser(regUser);
		bindEnt.setSzch(szch);
		bindEnt.setSqymc(sqymc);
		bindEnt.setSnbxh(snbxh);
		bindEnt.setIdentType(identType);
		IdentObj identObj = new IdentObj();
		identObj.setIdentCode(identCode);
		identObj.setIdentName(identName);
		bindEnt.setIdentObj(identObj);
		bindEnt.setIdentStatus(AppConfig.getProperty("status_normal", "status_code"));
		bindEnt.setBindTime(System.currentTimeMillis());
		bindEntDao.save(bindEnt);
        try {
		    regUser.getBindEnts().add(bindEnt);
			regUserDao.save(regUser);
		}catch (Exception e){
            bindEntDao.delete(bindEnt);
            throw new Exception("绑定企业已超过上限，请先解绑部分企业");
		}
		//保存当前企业信息到session
		handleSession.setVal(AppConfig.getProperty("ENT_SESSION_KEY", "SESSION_KEY"), bindEnt);
	}
	
	public Map<String,String> unBindent(){
		Map<String, String> returnMap = new HashMap<String, String>();
		//获取session用户信息
		Object regUserObj = handleSession.getVal(AppConfig.getProperty("USER_SESSION_KEY","SESSION_KEY"));
		if (regUserObj == null){
			returnMap.put("result",
			AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "用户未登录");
		    return returnMap;
		}
		Object bindEntObj = handleSession.getVal(AppConfig.getProperty("ENT_SESSION_KEY","SESSION_KEY")); 
		if (bindEntObj == null){
			returnMap.put("result",
			AppConfig.getProperty("fail", "return_code"));
			returnMap.put("description", "用户未以企业身份登录");
		    return returnMap;
		}
		RegUser regUser = (RegUser)regUserObj;
		BindEnt bindEnt = (BindEnt)bindEntObj;
		regUser.getBindEnts().remove(bindEnt);
		regUserDao.save(regUser);
		bindEntDao.delete(bindEnt);
		handleSession.removeVal(AppConfig.getProperty("ENT_SESSION_KEY", "SESSION_KEY"));
		returnMap.put("result",
				AppConfig.getProperty("success", "return_code"));
		returnMap.put("description", "已成功解除该企业绑定");
		return returnMap;
	}
	
	
}
